﻿using Microsoft.Office.Server.Search.Query;

namespace Trentacular.Office.Server.Search.FacetedSearch.Providers
{
    /// <summary>
    /// A facet provider implementatino that correlates the the SiteName and SiteTitle
    /// managed properties to a single facet.
    /// </summary>
    public class SiteFacetProvider : BaseFacetProvider
    {
        /// <summary>
        /// Gets the managed properties that need to be included in the facet query.
        /// </summary>
        /// <value>The managed properties to be included in the facet query.</value>
        public override string[] ManagedPropertiesToQuery
        {
            get { return new[] { "SiteName", "SiteTitle" }; }
        }

        protected int SiteNameFieldIndex;
        protected int SiteTitleFieldIndex;

        /// <summary>
        /// Initializes the facet provider before any rows have been iterated.
        /// </summary>
        /// <param name="resultTable">The result table.</param>
        public override void Initialize(ResultTable resultTable)
        {
            SiteNameFieldIndex = resultTable.GetOrdinal("SiteName");
            SiteTitleFieldIndex = resultTable.GetOrdinal("SiteTitle");
        }

        /// <summary>
        /// Processes a single row of the result table.
        /// </summary>
        /// <param name="resultTable">The result table.</param>
        public override void ProcessRow(ResultTable resultTable)
        {
            // If DBNull, lets get out of here
            if (resultTable.IsDBNull(SiteNameFieldIndex) ||
                resultTable.IsDBNull(SiteTitleFieldIndex))
                return;

            var siteUrl = resultTable.GetString(SiteNameFieldIndex);
            if (this.FacetTable.ContainsKey(siteUrl))
            {
                this.FacetTable[siteUrl].Count++;
                return;
            }

            var facet = BuildFacet(
                siteUrl,
                resultTable.GetString(SiteTitleFieldIndex)
                );

            facet.Count = 1;

            this.FacetTable[siteUrl] = facet;
        }

        /// <summary>
        /// Builds a new facet.
        /// </summary>
        /// <param name="siteUrl">The site URL.</param>
        /// <param name="siteTitle">The site title.</param>
        /// <returns>Newly constructed facet.</returns>
        protected virtual Facet BuildFacet(string siteUrl, string siteTitle)
        {
            return new Facet(
                FacetedSearchContext,
                Configuration,
                siteUrl,
                siteTitle,
                string.Format("(SiteName = '{0}')", siteUrl.Replace("'", "''"))
            );
        }
    }
}
